package com.liannong.controller;

import com.liannong.annotation.CommonAuth;
import com.liannong.common.Result;
import com.liannong.dto.WarehouseDTO;
import com.liannong.entity.Warehouse;
import com.liannong.entity.Product;
import com.liannong.service.WarehouseService;
import com.liannong.vo.WarehouseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController {

    private static final Logger log = LoggerFactory.getLogger(WarehouseController.class);

    @Autowired
    private WarehouseService warehouseService;

    /**
     * 添加仓库记录
     * @param warehouseDTO 仓库信息DTO
     * @return 添加结果
     */
    @PostMapping("/save")
    @CommonAuth
    public Result save(@RequestBody WarehouseDTO warehouseDTO) {
        log.info("添加仓库记录: {}", warehouseDTO);
        try {
            // 检查溯源码是否已存在
            if (warehouseDTO.getTraceCode() != null && !warehouseDTO.getTraceCode().isEmpty()) {
                Warehouse existingWarehouse = warehouseService.getByTraceCode(warehouseDTO.getTraceCode());
                if (existingWarehouse != null) {
                    log.warn("溯源码已存在: {}", warehouseDTO.getTraceCode());
                    return Result.error("400", "溯源码已存在，不能重复添加");
                }
            }
            
            // 如果提供了productId，检查是否存在于product表中
            Long productId = null;
            if (warehouseDTO.getProductId() != null && !warehouseDTO.getProductId().isEmpty()) {
                try {
                    productId = Long.parseLong(warehouseDTO.getProductId());
                    
                    // 检查商品是否存在
                    boolean productExists = warehouseService.checkProductExists(productId);
                    if (!productExists) {
                        log.warn("商品ID不存在: {}", productId);
                        return Result.error("400", "商品ID不存在，请先添加商品");
                    }
                    
                    // 检查该商品是否已有库存记录
                    boolean stockExists = warehouseService.checkProductStockExists(productId);
                    if (stockExists) {
                        log.warn("商品ID已有库存记录: {}", productId);
                        return Result.error("400", "该商品已有库存记录，请使用更新库存功能");
                    }
                } catch (NumberFormatException e) {
                    log.warn("商品ID格式不正确: {}", warehouseDTO.getProductId());
                    return Result.error("400", "商品ID格式不正确");
                }
            }
            
            // 将DTO转换为实体
            Warehouse warehouse = new Warehouse();
            warehouse.setTraceCode(warehouseDTO.getTraceCode());
            if (productId != null) {
                warehouse.setProductId(productId);
            }
            warehouse.setAmount(warehouseDTO.getAmount());
            
            // 优先使用DTO中的name，如果没有则使用productName
            if (warehouseDTO.getName() != null && !warehouseDTO.getName().isEmpty()) {
                warehouse.setName(warehouseDTO.getName());
            } else if (warehouseDTO.getProductName() != null && !warehouseDTO.getProductName().isEmpty()) {
                warehouse.setName(warehouseDTO.getProductName());
            } else {
                warehouse.setName("商品" + warehouseDTO.getTraceCode());
            }
            
            // 设置origin
            if (warehouseDTO.getOrigin() != null && !warehouseDTO.getOrigin().isEmpty()) {
                warehouse.setOrigin(warehouseDTO.getOrigin());
            } else {
                warehouse.setOrigin("未知");
            }
            
            // 设置温度
            if (warehouseDTO.getCurrentTemperature() != null) {
                warehouse.setNowTemp(warehouseDTO.getCurrentTemperature());
            }
            
            boolean success = warehouseService.addWarehouse(warehouse);
            if (success) {
                return Result.success();
            } else {
                return Result.error();
            }
        } catch (Exception e) {
            log.error("添加仓库记录失败", e);
            return Result.error();
        }
    }

    /**
     * 更新仓库温度
     * @param id 仓库ID
     * @param temperature 温度
     * @return 更新结果
     */
    @PutMapping("/updateTemperature/{id}")
    @CommonAuth
    public Result updateTemperature(
            @PathVariable Integer id,
            @RequestParam Integer temperature) {
        log.info("更新仓库温度: id={}, temperature={}", id, temperature);
        boolean success = warehouseService.updateTemperature(id, temperature);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 更新发货日期
     * @param id 仓库ID
     * @param sendDate 发货日期
     * @return 更新结果
     */
    @PutMapping("/updateSendDate/{id}")
    @CommonAuth
    public Result updateSendDate(
            @PathVariable Integer id,
            @RequestParam LocalDate sendDate) {
        log.info("更新发货日期: id={}, sendDate={}", id, sendDate);
        boolean success = warehouseService.updateSendDate(id, sendDate);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 更新收货日期
     * @param id 仓库ID
     * @param recvDate 收货日期
     * @return 更新结果
     */
    @PutMapping("/updateRecvDate/{id}")
    @CommonAuth
    public Result updateRecvDate(
            @PathVariable Integer id,
            @RequestParam LocalDate recvDate) {
        log.info("更新收货日期: id={}, recvDate={}", id, recvDate);
        boolean success = warehouseService.updateRecvDate(id, recvDate);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 根据溯源码查询仓库记录
     * @param traceCode 溯源码
     * @return 仓库记录
     */
    @GetMapping("/findByTraceCode/{traceCode}")
    @CommonAuth
    public Result findByTraceCode(@PathVariable String traceCode) {
        log.info("根据溯源码查询仓库记录: traceCode={}", traceCode);
        Warehouse warehouse = warehouseService.getByTraceCode(traceCode);
        log.info("查询结果: {}", warehouse);
        if (warehouse != null) {
            return Result.success(warehouse);
        } else {
            return Result.error();
        }
    }

    /**
     * 根据产品名称查询仓库记录
     * @param name 产品名称
     * @return 仓库记录列表
     */
    @GetMapping("/findByName/{name}")
    @CommonAuth
    public Result findByName(@PathVariable String name) {
        log.info("根据产品名称查询仓库记录: name={}", name);
        List<Warehouse> warehouseList = warehouseService.getByName(name);
        log.info("查询结果数量: {}", warehouseList.size());
        return Result.success(warehouseList);
    }

    /**
     * 获取所有仓库记录列表
     * @return 仓库VO列表
     */
    @GetMapping("/findAll")
    @CommonAuth
    public Result findAll() {
        log.info("获取所有仓库记录列表");
        try {
            List<WarehouseVO> warehouseList = warehouseService.getWarehouseList();
            log.info("查询成功，返回记录数: {}", warehouseList.size());
            return Result.success(warehouseList);
        } catch (Exception e) {
            log.error("查询仓库列表失败: ", e);
            return Result.error();
        }
    }

    /**
     * 获取仓库详情
     * @param warehouseId 仓库ID
     * @return 仓库VO对象
     */
    @GetMapping("/findById/{warehouseId}")
    @CommonAuth
    public Result findById(@PathVariable Integer warehouseId) {
        log.info("获取仓库详情: warehouseId={}", warehouseId);
        try {
            WarehouseVO warehouseVO = warehouseService.getWarehouseDetail(warehouseId);
            log.info("查询结果: {}", warehouseVO);
            if (warehouseVO != null) {
                return Result.success(warehouseVO);
            } else {
                return Result.error();
            }
        } catch (Exception e) {
            log.error("获取仓库详情失败: ", e);
            return Result.error();
        }
    }

    /**
     * 检查仓库是否可用
     * @param warehouseId 仓库ID
     * @return 是否可用
     */
    @GetMapping("/checkAvailable/{warehouseId}")
    @CommonAuth
    public Result checkAvailable(@PathVariable Integer warehouseId) {
        log.info("检查仓库是否可用: warehouseId={}", warehouseId);
        try {
            boolean available = warehouseService.checkWarehouseAvailable(warehouseId);
            log.info("检查结果: {}", available);
            if (available) {
                return Result.success();
            } else {
                return Result.error();
            }
        } catch (Exception e) {
            log.error("检查仓库是否可用失败: ", e);
            return Result.error();
        }
    }

    /**
     * 更新库存
     * @param productId 商品ID
     * @param stockMap 新的库存信息
     * @return 更新结果
     */
    @PutMapping("/updateStock/{productId}")
    @CommonAuth
    public Result updateStock(@PathVariable String productId, @RequestBody Map<String, Object> stockMap) {
        log.info("updating stock for product ID: {}", productId);
        try {
            // 从请求体中获取库存量
            Object amountObj = stockMap.get("amount");
            if (amountObj == null) {
                return Result.error("400", "缺少必需的参数");
            }
            int amount;
            try {
                // 尝试转换为整数
                amount = Integer.parseInt(amountObj.toString());
            } catch (NumberFormatException e) {
                log.error("Invalid amount format: {}", amountObj);
                return Result.error("400", "参数格式错误");
            }
            log.info("New stock amount: {}", amount);
            
            // 尝试解析productId为Long类型
            Long productIdLong;
            try {
                productIdLong = Long.parseLong(productId);
                log.info("Using product ID: {}", productIdLong);
                // 使用productId更新库存
                warehouseService.updateWarehouseAmount(productIdLong, amount);
                return Result.success("库存更新成功");
            } catch (NumberFormatException e) {
                log.info("productId不是数字格式，尝试作为traceCode处理");
                // 如果productId不是数字，当作traceCode处理
                String traceCode = productId;
                // 使用traceCode更新库存
                boolean success = warehouseService.updateWarehouseAmountByTraceCode(traceCode, amount);
                if (success) {
                    return Result.success("库存更新成功");
                } else {
                    return Result.error("400", "无效的产品ID或追溯码");
                }
            }
        } catch (Exception e) {
            log.error("Error updating stock", e);
            return Result.error("500", "服务器错误");
        }
    }

    /**
     * 根据溯源码更新库存
     * @param traceCode 溯源码
     * @param stockMap 新的库存信息
     * @return 更新结果
     */
    @PutMapping("/updateStockByTraceCode/{traceCode}")
    @CommonAuth
    public Result updateStockByTraceCode(@PathVariable String traceCode, @RequestBody Map<String, Object> stockMap) {
        log.info("根据溯源码更新库存: traceCode={}", traceCode);
        try {
            // 从请求体中获取库存量
            Object amountObj = stockMap.get("amount");
            if (amountObj == null) {
                return Result.error("400", "缺少必需的参数");
            }
            int amount;
            try {
                // 尝试转换为整数
                amount = Integer.parseInt(amountObj.toString());
            } catch (NumberFormatException e) {
                log.error("Invalid amount format: {}", amountObj);
                return Result.error("400", "参数格式错误");
            }
            log.info("New stock amount for traceCode {}: {}", traceCode, amount);
            
            boolean success = warehouseService.updateWarehouseAmountByTraceCode(traceCode, amount);
            if (success) {
                return Result.success("库存更新成功");
            } else {
                return Result.error("400", "无效的追溯码");
            }
        } catch (Exception e) {
            log.error("根据溯源码更新库存失败", e);
            return Result.error("500", "服务器错误");
        }
    }

    /**
     * 关联仓库记录与商品
     * @return 关联结果
     */
    @PostMapping("/linkToProducts")
    @CommonAuth
    public Result linkWarehouseToProducts() {
        log.info("Linking warehouse records to products");
        try {
            warehouseService.linkWarehouseToProducts();
            return Result.success("仓库记录关联商品成功");
        } catch (Exception e) {
            log.error("Error linking warehouse to products", e);
            return Result.error("500", "服务器错误");
        }
    }
    
    /**
     * 根据商品ID获取商品信息
     * @param productId 商品ID
     * @return 商品信息
     */
    @GetMapping("/getProductInfo/{productId}")
    @CommonAuth
    public Result getProductInfo(@PathVariable Long productId) {
        log.info("获取商品信息: productId={}", productId);
        try {
            if (productId == null) {
                return Result.error("400", "商品ID不能为空");
            }
            
            // 检查商品是否存在并获取信息
            Product product = warehouseService.getProductInfo(productId);
            if (product == null) {
                log.warn("商品ID不存在: {}", productId);
                return Result.error("400", "商品ID不存在");
            }
            
            log.info("查询到商品信息: id={}, name={}, traceCode={}", 
                product.getProductId(), product.getName(), product.getTraceCode());
            
            return Result.success(product);
        } catch (Exception e) {
            log.error("获取商品信息失败", e);
            return Result.error("500", "服务器错误");
        }
    }
    
    /**
     * 创建新的仓库记录
     * @param warehouse 仓库信息
     * @return 创建结果
     */
    @PostMapping("/create")
    @CommonAuth
    public Result createWarehouse(@RequestBody Warehouse warehouse) {
        log.info("Creating new warehouse record for product ID: {}", warehouse.getProductId());
        try {
            if (warehouse.getProductId() == null) {
                return Result.error("400", "商品ID不能为空");
            }
            if (warehouse.getAmount() == null) {
                return Result.error("400", "库存数量不能为空");
            }
            
            // 检查商品是否存在
            boolean productExists = warehouseService.checkProductExists(warehouse.getProductId());
            if (!productExists) {
                log.warn("商品ID不存在: {}", warehouse.getProductId());
                return Result.error("400", "商品ID不存在，请先添加商品");
            }
            
            // 检查该商品是否已有库存记录
            boolean stockExists = warehouseService.checkProductStockExists(warehouse.getProductId());
            if (stockExists) {
                log.warn("商品ID已有库存记录: {}", warehouse.getProductId());
                return Result.error("400", "该商品已有库存记录，请使用更新库存功能");
            }
            
            Warehouse created = warehouseService.createWarehouse(
                warehouse.getProductId(), 
                warehouse.getAmount(), 
                warehouse.getOrigin(), 
                warehouse.getName(),
                warehouse.getNowTemp()
            );
            
            return Result.success(created);
        } catch (Exception e) {
            log.error("Error creating warehouse record", e);
            return Result.error("500", "服务器错误");
        }
    }
    
    /**
     * 删除仓库记录
     * @param warehouseId 仓库ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{warehouseId}")
    @CommonAuth
    public Result deleteWarehouse(@PathVariable Integer warehouseId) {
        log.info("删除仓库记录: warehouseId={}", warehouseId);
        try {
            if (warehouseId == null) {
                return Result.error("400", "仓库ID不能为空");
            }
            
            // 检查仓库记录是否存在
            Warehouse warehouse = warehouseService.getById(warehouseId);
            if (warehouse == null) {
                log.warn("仓库记录不存在: warehouseId={}", warehouseId);
                return Result.error("400", "仓库记录不存在");
            }
            
            // 执行删除操作
            boolean success = warehouseService.removeById(warehouseId);
            if (success) {
                log.info("删除仓库记录成功: warehouseId={}", warehouseId);
                return Result.success("删除成功");
            } else {
                log.error("删除仓库记录失败: warehouseId={}", warehouseId);
                return Result.error("500", "删除失败");
            }
        } catch (Exception e) {
            log.error("删除仓库记录异常", e);
            return Result.error("500", "服务器错误");
        }
    }
    
    /**
     * 批量删除仓库记录
     * @param ids 仓库ID集合
     * @return 删除结果
     */
    @DeleteMapping("/deleteBatch")
    @CommonAuth
    public Result deleteBatchWarehouse(@RequestBody Map<String, List<Integer>> payload) {
        List<Integer> ids = payload.get("ids");
        log.info("批量删除仓库记录: ids={}", ids);
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("400", "仓库ID列表不能为空");
            }
            
            // 执行批量删除操作
            boolean success = warehouseService.removeByIds(ids);
            if (success) {
                log.info("批量删除仓库记录成功: ids={}", ids);
                return Result.success("批量删除成功");
            } else {
                log.error("批量删除仓库记录失败: ids={}", ids);
                return Result.error("500", "批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除仓库记录异常", e);
            return Result.error("500", "服务器错误");
        }
    }

    /**
     * 更新仓库记录的商品ID
     * @param warehouseId 仓库ID
     * @param requestMap 请求体，包含productId
     * @return 更新结果
     */
    @PutMapping("/updateProductId/{warehouseId}")
    @CommonAuth
    public Result updateProductId(@PathVariable Integer warehouseId, @RequestBody Map<String, Object> requestMap) {
        log.info("更新仓库记录商品ID: warehouseId={}", warehouseId);
        try {
            Object productIdObj = requestMap.get("productId");
            if (productIdObj == null) {
                return Result.error("400", "商品ID不能为空");
            }
            
            Long productId;
            try {
                if (productIdObj instanceof Integer) {
                    productId = ((Integer) productIdObj).longValue();
                } else if (productIdObj instanceof Long) {
                    productId = (Long) productIdObj;
                } else {
                    productId = Long.parseLong(productIdObj.toString());
                }
            } catch (NumberFormatException e) {
                return Result.error("400", "商品ID格式不正确");
            }
            
            // 检查仓库记录是否存在
            Warehouse warehouse = warehouseService.getById(warehouseId);
            if (warehouse == null) {
                log.warn("仓库记录不存在: warehouseId={}", warehouseId);
                return Result.error("400", "仓库记录不存在");
            }
            
            // 检查商品是否存在
            boolean productExists = warehouseService.checkProductExists(productId);
            if (!productExists) {
                log.warn("商品ID不存在: {}", productId);
                return Result.error("400", "商品ID不存在");
            }
            
            // 更新仓库记录的商品ID
            warehouse.setProductId(productId);
            boolean success = warehouseService.updateById(warehouse);
            
            if (success) {
                log.info("更新仓库记录商品ID成功: warehouseId={}, productId={}", warehouseId, productId);
                return Result.success("更新成功");
            } else {
                log.error("更新仓库记录商品ID失败: warehouseId={}, productId={}", warehouseId, productId);
                return Result.error("500", "更新失败");
            }
        } catch (Exception e) {
            log.error("更新仓库记录商品ID异常", e);
            return Result.error("500", "服务器错误");
        }
    }
} 